<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/10/16
 * Time: 9:45
 */

namespace app\admin\controller;

use think\Controller;
use think\Cookie;
use \think\Request;
use think\Session;
use think\Captcha;

class Login extends \think\Controller
{
    private $_model;

    public function _initialize()
    {
        session_start();
        $this->assign('LoginUserInfo', $this->LoginUserInfo);
        //获取当前用户的权限信息
        $this->assign('ruleLists', $this->LoginUserInfo['CurrPower']);
    }

    public function recordSystemLog($arr)
    {
        $model = new \app\admin\model\Log();
        $model->add($arr);
    }

    /**
     * 登录验证
     */
    public function login()
    {
        if (request()->isPost()) {
            $username = trim(input("request.username"));//auth
            $password = trim(input("request.password"));//auth
            $yzm = trim(input("request.yzm"));//auth

            if (!captcha_check($yzm)){
                apiReturnData(array('err' => 1, 'msg' => '验证码不正确'));
            }

            /*
             * 我的验证码start
            $fwq_yzm = $_SESSION['yzm'];
           if ($yzm != $fwq_yzm) {
                apiReturnData(array('err' => 1, 'msg' => '验证码不正确'));
            }
            */

            $model = new \app\admin\model\User();
            $res = $model->login($username, $password);

            if ($res['err'] == 0) {

                $data = array(
                    'UserInfo' => $res['data'],
                    'FirstDep' => array(),
                    'SecondDep' => array(),
                    'Group' => array(),
                    'CurrPower' => array(),
                    'isSupperManager' => 0,//是否是超级管理员 0不是  1是
                );

                //查询所属部门
                $depModel = new \app\admin\model\Dep();
                if ($res['data']['first_depid'])//一级部门
                {
                    $depInfo = $depModel->getID($res['data']['first_depid']);
                    $data['FirstDep'] = $depInfo;
                }
                if ($res['data']['depid'])//二级部门
                {
                    $depInfo = $depModel->getID($res['data']['depid']);
                    $data['SecondDep'] = $depInfo;
                }


                //查询所属角色
                $groupLists = getUserAllGroup($data['UserInfo']['id']);
                $data['Group'] = $groupLists;

                //查询判断是否允许登陆系统
                if(is_allow_login_system($data['Group'])==0)
                {
                    apiReturnData(array('err' => 1, 'msg' => '对不起，您无权登录系统'));
                }

                //查询是否是超级管理员
                $data['isSupperManager'] = isSupperManager($data['Group']);
                $tempRuleLists = array();

                if ($data['isSupperManager'] == 0) {
                    //获取当前用户的权限信息
                    foreach ($data['Group'] as $k => $v) {
                        $ruleModel = new \app\admin\model\Rule();
                        $ruleLists = $ruleModel->getAll(array('gid' => $v['id']));
                        foreach ($ruleLists as $key => $val) {
                            $tempRuleLists[] = $val['rid'];
                        }
                    }
                    if(!empty($tempRuleLists))
                    {
                        $tempRuleLists=array_unique($tempRuleLists);
                    }
                }
                $data['CurrPower'] = $tempRuleLists;

                //获取系统所有权限
                $systemAllPower = (new \app\admin\model\Ruleobj())->getDataForWheres(array('path' => array('neq', "")));
                $data['systemAllPowerPath'] = $this->getAllPowerPath($systemAllPower);

                $systemAllPower = $this->makeAllPowerList($systemAllPower);
                $data['systemAllPower'] = $systemAllPower;

                //设置cookie 和session
                Session::set('UserInfo', json_encode($data, true));
//                Cookie::set('UserInfo', encodeCookie($data));//cookies 如果太大php报错 500错误

                apiReturnData(array('err' => 0, 'msg' => '登陆成功', 'data' => $data['UserInfo']));
            } else {
                apiReturnData(array('err' => 1, 'msg' => $res['msg']));
            }


        }

        return view('login');

    }


    private function getAllPowerPath($list)
    {
        if (empty($list)) {
            return array();
        }
        $tempList = array();
        foreach ($list as $k => $v) {
            if (!empty($v['path'])) {
                $temp = explode(",", $v['path']);
                foreach ($temp as $k1 => $v1) {
                    if ($v1) {
                        $tempList[] = $v1;
                    }
                }

            }
        }
        return $tempList;
    }

    private function makeAllPowerList($list, $key = "path")
    {
        if (empty($list)) {
            return array();
        }
        $tempList = array();
        foreach ($list as $k => $v) {
            $sub = strtolower($v[$key]);
            $temp = explode(",", $sub);
            foreach ($temp as $k1 => $v1) {
                if ($v1) {
                    $tempList[$v1] = $v;
                }
            }
        }
        return $tempList;
    }

    /**
     * 退出登录
     */
    public function logout()
    {
//        session(null);
        Session::clear();
        Cookie::clear('logname');

        return view('logout');
    }

    public function checkCode()
    {
        ob_clean();
        include_once(dirname(realpath(APP_PATH)) . "/vendor/myCal/Checkcode.php");

        $_vc = new \Checkcode();  //实例化一个对象
        $_vc->doimg();
        $code = $_vc->getCode();
        $_SESSION['yzm'] = $code;//验证码保存到SESSION中

    }
}